<template>
  <el-dialog
      v-model="visible"
      title="导出预约记录"
      width="420px"
      :close-on-click-modal="false"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="时间范围">
        <el-date-picker
            v-model="form.daterange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleExport">导出 CSV</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import request from "@/apps/admin/utils/request.js";

const props = defineProps({
  modelValue: Boolean,
  type: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'export'])

const visible = ref(props.modelValue)
watch(() => props.modelValue, val => (visible.value = val))
watch(visible, val => emit('update:modelValue', val))

const form = ref({
  daterange: []
})

const close = () => {
  visible.value = false
}

const handleExport = async () => {
  const [start, end] = form.value.daterange || []
  if (!start || !end) {
    ElMessage.warning('请选择时间范围')
    return
  }

  try {
    const response = await request.get('/v1/admin/export', {
      params: {
        startTime: start,
        endTime: end,
        type: props.type
      },
      responseType: 'text'  // 这里改成 text
    })
    //console.log('导出接口返回:', response)
    // response.data 是 CSV 文本字符串，手动生成 Blob

    const BOM = '\uFEFF'
    const blob = new Blob([BOM + response], {
      type: 'text/csv;charset=utf-8'
    })
    const url = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'reservations.csv')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
    emit('export', { startTime: start, endTime: end, type: props.type })
    close()
  } catch (error) {
    console.error(error)
    ElMessage.error('导出失败')
  }
}


</script>